package cn.genmer.record.controller;

import cn.genmer.record.common.CommonResult;
import cn.genmer.record.dto.RecordResult;
import cn.genmer.record.dto.RecordDTO;
import cn.genmer.record.dto.form.RecordForm;
import cn.genmer.record.model.CodeRecord;
import cn.genmer.record.model.Coder;
import cn.genmer.record.service.ICoderService;
import cn.genmer.record.service.IRecordService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.web.bind.annotation.*;
import util.GeneratID;
import util.IPUtils;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 记录行数控制器
 */
@RestController
@RequestMapping("/record")
@Api(tags = "记录行数控制器")
//@CrossOrigin(origins = "http://localhost:8080", maxAge = 3600)
public class RecordController {

    @Autowired
    private IRecordService recordService;

    @Autowired
    private ICoderService coderService;

    @ApiOperation("新增记录")
    @PostMapping("/add")
    public CommonResult addRecord(HttpServletRequest request, @RequestBody RecordForm recordForm){
        CodeRecord record = new CodeRecord();
        record.setId(GeneratID.getGeneratID().toString());
        record.setCreateTime(LocalDateTime.now());

        BeanUtils.copyProperties(recordForm, record);

        record.setIpAddress(IPUtils.getIpAddr(request));
        // 获取springSecurity的用户信息
        String username = request.getUserPrincipal().getName();
        // 根据登陆用户名获取用户昵称
        QueryWrapper<Coder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        Coder coder = coderService.getOne(wrapper);
        if (coder == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        record.setOperatorName(coder.getNickName());
        record.setOperatorId(coder.getId());

        // TODO 接入DAO存储到数据库
        try {
            recordService.save(record);
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.error(e.toString());
        }
        return CommonResult.success("新增记录完成");
    }

    @ApiOperation("查询记录 - 自动根据登陆用户获取")
    @GetMapping("/getAll")
    public CommonResult getAll(HttpServletRequest request){
        // 获取登陆用户信息
        Coder coder = getUser(request);
        RecordResult recordResult = new RecordResult();
        try {
            QueryWrapper<CodeRecord> byoperator = new QueryWrapper<>();
            byoperator.eq("operator_id", coder.getId());
            List<CodeRecord> result = new ArrayList<>();
            result = recordService.list(byoperator);
            // 获取当前用户提交的记录数量
            int count = recordService.count(byoperator);
            // 添加记录行数的信息
            byoperator.select(" ifnull(sum(affec_rows),0) as total");
            Map<String, Object> map = recordService.getMap(byoperator);
            // 设置返回结果
            recordResult.setSumbmitNumber(count);
            recordResult.setTotalRow(Integer.valueOf(map.get("total").toString()));

            recordResult.setRecords(transfer(result));
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.error(e.toString());
        }
        return CommonResult.success(recordResult);
    }

    @ApiOperation("查询记录总数 - 自动根据登陆用户获取")
    @GetMapping("/getCount")
    public CommonResult getCount(HttpServletRequest request){
        // 获取登陆用户信息


        Coder coder = getUser(request);
        RecordResult recordCount = new RecordResult();
        try {
            // 新建条件查询
            QueryWrapper<CodeRecord> byoperator = new QueryWrapper<>();
            // 添加登陆用户信息
            byoperator.eq("operator_id", coder.getId());
            // 获取当前用户提交的记录数量
            int count = recordService.count(byoperator);
            // 添加记录行数的信息
            byoperator.select(" ifnull(sum(affec_rows),0) as total");
            Map<String, Object> map = recordService.getMap(byoperator);
            // 设置返回结果
            recordCount.setSumbmitNumber(count);
            recordCount.setTotalRow(Integer.valueOf(map.get("total").toString()));
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.error(e.toString());
        }
        return CommonResult.success(recordCount);
    }


    @ApiOperation("删除记录 - 自动根据登陆用户获取")
    @GetMapping("/delete")
    public CommonResult delete(HttpServletRequest request, @RequestParam String id){
        // 获取登陆用户信息
        Coder coder = getUser(request);
        try {
            // 新建条件查询
            QueryWrapper<CodeRecord> query = new QueryWrapper<>();
            // 添加登陆用户信息
            query.eq("id", id);
            // 取得要删除记录的记录
            CodeRecord record = recordService.getOne(query);
            if (record == null){
                return CommonResult.error("找不到对应id的记录");
            }
            // 获取对应的操作人
            Coder operator = coderService.getById(record.getOperatorId());
            // 只有记录炒作人可删除其创建的记录
            if (record.getOperatorId() != null && operator.getId().equalsIgnoreCase(coder.getId())){
                boolean isDelete = recordService.removeById(id);
                if (isDelete){
                    return CommonResult.success("删除成功");
                } else {
                    return CommonResult.error("删除失败");
                }
            }else {
                return CommonResult.error("当前id不是您的记录，无法删除");
            }
        }catch (Exception e){
            e.printStackTrace();
            return CommonResult.error(e.toString());
        }
    }
    /**
     * codeRecord转为recordDTO
     * @param list
     * @return
     */
    private List<RecordDTO> transfer(List<CodeRecord> list){
        ArrayList<RecordDTO> objects = new ArrayList<>();
        for (CodeRecord record: list){
            RecordDTO recordDTO = new RecordDTO();
            BeanUtils.copyProperties(record, recordDTO);
            objects.add(recordDTO);
        }

        return objects;
    }

    /**
     *  获取用户信息公共方法
     * @param request
     * @return
     */
    private Coder getUser(HttpServletRequest request){
        // 获取springSecurity的用户信息
        String username = request.getUserPrincipal().getName();
        // 根据登陆用户名获取用户昵称
        QueryWrapper<Coder> wrapper = new QueryWrapper<>();
        wrapper.eq("user_name", username);
        Coder coder = coderService.getOne(wrapper);
        if (coder == null){
            throw new UsernameNotFoundException("用户名不存在");
        }
        return coder;
    }
}
